package com.push.notifications;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Queue;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;


public class ServiceQueueDownloadUtil {
	public static Queue<IDownloadedItem> downloadQueue = new LinkedList<IDownloadedItem>();
	public static DownloadThread download;
	public static final String MESSAGE_ERROR = "Download unsuccessful";
	public static final String MESSAGE_COMPLETE = "Download successful";
	private boolean downloadState = false;

	private static OnDownloadCompleteListener onDownloadCompleteListener;
	private static OnDownloadStartListener onDownloadStartListener;

	public static void pushDownloadTaskQueue(Context context,
			IDownloadedItem item) {
		DownloadThread.notificationId++;
		ServiceQueueDownloadUtil.notifyDownloadMessage(context,
				item.getFileName() + ": " + "0%",
				DownloadThread.notificationId, item.getName(), (byte) 1);
		synchronized (downloadQueue) {
			downloadQueue.add(item);
		}
	}

	public static void runDownloadQueue(Context context) {
		if (!downloadQueue.isEmpty()) {
			try {
				synchronized (downloadQueue) {
					IDownloadedItem downloadItem = downloadQueue.remove();
					download = new DownloadThread(context, downloadItem);
					download.setOnDownloadCompleteListener(onDownloadCompleteListener);
					download.setOnDownloadStartListener(onDownloadStartListener);
				}
			} catch (Exception e) {
				e.printStackTrace();
				cancelTask();
			}
		}

	}

	public static void cancelTask() {
		download.onCancelled();
	}

	public static void cancelAll() {
		if (download != null)
			download.onCancelledAll();
	}

	public static void requestDumpGet(String url) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);

		HttpParams httpParams = httpGet.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		try {
			httpclient.execute(httpGet);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static InputStream getDownloadStream(String url, IDownloadedItem item)
			throws IOException, Exception {
		HttpClient httpclient = new DefaultHttpClient();
		HttpResponse response;
		try {
			HttpGet httpGet = new HttpGet(url);
			HttpParams httpParams = httpGet.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
			HttpConnectionParams.setSoTimeout(httpParams, 10000);
			response = httpclient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200 || statusCode == 206) {
				int contentLength = Integer.parseInt(response
						.getHeaders("Content-Length")[0].getValue());
				if (contentLength <= 0)
					return null;
				item.setFileSize(contentLength);
				HttpEntity resEntity = response.getEntity();
				return resEntity.getContent();
			} else {
				return null;
			}

		} catch (ClientProtocolException ex) {
			throw new IOException(ex.getLocalizedMessage());
		} catch (NullPointerException ex) {
			throw new IOException(ex.getLocalizedMessage());
		} catch (IOException ex) {
			throw ex;
		} catch (Exception ex) {
			throw ex;
		} finally {
			// try {httpclient.getConnectionManager().shutdown();} catch
			// (Exception ignore) {}
		}
	}

	public static void notifyDownloadMessage(Context context, String message,
			int downloadId, String title, byte iconType) {
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.cancelAll();
		Notification notification = null;
		switch (iconType) {
		case 1:
			notification = new Notification(
					R.drawable.download_icon_downloading, message,
					System.currentTimeMillis());
			break;
		case 2:
			notification = new Notification(R.drawable.download_icon_failed,
					message, System.currentTimeMillis());
			break;
		default:
			notification = new Notification(R.drawable.download_icon, message,
					System.currentTimeMillis());
		}
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent viewIntent = new Intent("Test");
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				viewIntent, 0);
		notification.setLatestEventInfo(context, title, message, pendingIntent);
		notificationManager.notify(123 + downloadId, notification);
	}

	public static void cancelDownloadNotification(Context context,
			int downloadId) {
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.cancel(123 + downloadId);
	}

	public static OnDownloadCompleteListener getOnDownloadCompleteListener() {
		return onDownloadCompleteListener;
	}

	public static void setOnDownloadCompleteListener(
			OnDownloadCompleteListener onDownloadCompleteListener) {
		ServiceQueueDownloadUtil.onDownloadCompleteListener = onDownloadCompleteListener;
	}

	public static OnDownloadStartListener getOnDownloadStartListener() {
		return onDownloadStartListener;
	}

	public static void setOnDownloadStartListener(
			OnDownloadStartListener onDownloadStartListener) {
		ServiceQueueDownloadUtil.onDownloadStartListener = onDownloadStartListener;
	}

	public boolean downloadState() {
		return downloadState;
	}
}
